package com.songshuai.webapi.baseapi.utils;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.songshuai.webapi.baseapi.constant.BaseConstant;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.enumerations.sales.error.SopImgError;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class QiNiuUploadUtil {

    //这几个登录七牛 账号里面可以找到
    private String access_key; //设置账号的access_key

    private String secret_key;//设置账号的secret_key

    private String bucketname; //要上传的空间,对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）

    //密钥配置
    private Auth auth;
    //构造一个带指定Zone对象的配置类
    private Configuration cfg;
    //创建上传对象
    private UploadManager uploadManager;

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public QiNiuUploadUtil() {
    }

    private QiNiuUploadUtil(String access_key, String secret_key, String bucketname) {
        this.access_key = access_key;
        this.secret_key = secret_key;
        this.bucketname = bucketname;
        this.auth = Auth.create(access_key, secret_key);
        this.cfg = new Configuration(Zone.zone0());
        this.uploadManager = new UploadManager(cfg);
    }

    public String getParam(){
        String s = "";
        s+="access_key：" +access_key;
        s+="secret_key："+secret_key;
        s+="bucketname："+bucketname;
        return s;
    }

    /**
     * 初始化对象
     *
     * @param access_key
     * @param secret_key
     * @param bucketname
     * @return
     */
    public static QiNiuUploadUtil build(String access_key, String secret_key, String bucketname) {
        return new QiNiuUploadUtil(access_key, secret_key, bucketname);
    }

    /**
     * MultipartFile 上传文件流
     *
     * @param file    上传文件流
     * @param imgName 文件名
     * @return
     * @throws Exception
     */

    public Map<String, Object> uploadImg(MultipartFile file, String imgName) throws Exception {
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String contentType = file.getContentType();   //文件类型
        String[] content = contentType.split("/");
        String originalFileName = file.getOriginalFilename();
        if (content.length > 0) {
            /*if ("image".equalsIgnoreCase(content[0])) {*/
                InputStream inputStream = file.getInputStream();
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[600]; //buff用于存放循环读取的临时数据
                int rc = 0;
                while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                byte[] uploadBytes = swapStream.toByteArray();

                Response response = uploadManager.put(uploadBytes, imgName, getUpToken());
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                return getResult(putRet.key, contentType, imgName, originalFileName, ResultStatus.SUCCESS.getErrorCode(), ResultStatus.SUCCESS.getErrorMsg());
            /*} else {
                log.info("判断为非图片文件");
                return getResult("", contentType, imgName, originalFileName, SopImgError.ERROR_IMG_TYPE.getCode(), SopImgError.ERROR_IMG_TYPE.getMsg());
            }*/
        } else {
            //非常规文件
            log.info("非常规文件");
            return getResult("", contentType, imgName, originalFileName, SopImgError.ERROR_UNIDENTIFIABLE_IMG_TYPE.getCode(), SopImgError.ERROR_UNIDENTIFIABLE_IMG_TYPE.getMsg());
        }
    }

    /**
     * 获取下载文件路径，即：donwloadUrl
     *
     * @return
     */
    public String getDownloadUrl(String targetUrl) {
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        return downloadUrl;
    }

    /**
     * 组装返回参数
     *
     * @param putRetKey        上传图片接口返回key
     * @param contentType      文件类型信息
     * @param imgName          新图片名字
     * @param originalFileName 原图片名字
     * @param code             返回码
     * @param msg              信息
     * @return
     */
    Map<String, Object> getResult(String putRetKey, String contentType, String imgName, String originalFileName, Integer code, String msg) {
        Map<String, Object> result = new HashMap<>();
        result.put("putRetKey", putRetKey);
        result.put("pictureType", contentType);
        result.put("imgName", imgName);
        result.put("originalName", originalFileName);
        result.put(BaseConstant.STR_CODE, code);
        result.put(BaseConstant.STR_MSG, msg);
        return result;
    }

}
